<template>
  <div class="caregiver-meal-container">
    <div class="header">
      <h2>餐饮记录</h2>
      <p>管理您负责的长者餐饮记录</p>
    </div>

    <!-- 搜索和筛选区域 -->
    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <el-row :gutter="20">
        <!-- 1. 长者姓名筛选：可输入+下拉选择 -->
        <el-col :span="6">
          <el-select v-model="searchParams.elderId"
                     placeholder="搜索长者姓名"
                     clearable
                     filterable
                     @change="handleElderChange"
                     @clear="handleSearch"
          >
            <el-option v-for="elder in elderList"
                       :key="elder.elderId"
                       :label="elder.name"
                       :value="elder.elderId.toString()"
            />
          </el-select>
        </el-col>

        <!-- 2. 餐饮类型筛选 -->
        <el-col :span="6">
          <el-select
              v-model="searchParams.mealType"
              placeholder="选择餐饮类型"
              clearable
              @change="handleSearch"
              @clear="handleSearch"
          >
            <el-option label="早餐" value="早餐" />
            <el-option label="午餐" value="午餐" />
            <el-option label="晚餐" value="晚餐" />
            <el-option label="加餐" value="加餐" />
          </el-select>
        </el-col>

        <!-- 3. 用餐时间筛选 -->
        <el-col :span="8">
          <el-date-picker
              v-model="searchParams.mealDate"
              type="date"
              placeholder="选择用餐日期"
              @change="handleSearch"
              @clear="handleSearch"
          />
        </el-col>

        <el-col :span="4">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 操作按钮 -->
    <div class="action-section">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增餐饮记录
      </el-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="elderName" label="长者姓名" width="120" />
        <el-table-column prop="mealType" label="餐饮类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getMealTypeTag(row.mealType)">
              {{ row.mealType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="mealTime" label="用餐时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.mealTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="foodContent" label="食物内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="intakeAmount" label="摄入量" width="100">
          <template #default="{ row }">
            <el-tag :type="getIntakeTag(row.intakeAmount)">
              {{ row.intakeAmount }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="specialDiet" label="特殊饮食" width="120" />
        <el-table-column prop="createTime" label="记录时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" fixed="right">
          <template #default="{ row }">
            <el-button
              size="small"
              type="primary"
              link
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
<!--            <el-button-->
<!--              size="small"-->
<!--              type="danger"-->
<!--              link-->
<!--              @click="handleDelete(row.mealId)"-->
<!--            >-->
<!--              删除-->
<!--            </el-button>-->
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="长者" prop="elderId">
          <el-select
            v-model="formData.elderId"
            placeholder="选择长者"
            style="width: 100%"
            :disabled="isEdit"
          >
            <el-option
              v-for="elder in elderList"
              :key="elder.elderId"
              :label="elder.name"
              :value="elder.elderId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="餐饮类型" prop="mealType">
          <el-select
            v-model="formData.mealType"
            placeholder="选择餐饮类型"
            style="width: 100%"
          >
            <el-option label="早餐" value="早餐" />
            <el-option label="午餐" value="午餐" />
            <el-option label="晚餐" value="晚餐" />
            <el-option label="加餐" value="加餐" />
          </el-select>
        </el-form-item>
        <el-form-item label="用餐时间" prop="mealTime">
          <el-date-picker
            v-model="formData.mealTime"
            type="datetime"
            placeholder="选择用餐时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="食物内容" prop="foodContent">
          <el-input
            v-model="formData.foodContent"
            type="textarea"
            :rows="3"
            placeholder="请输入食物内容"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="摄入量" prop="intakeAmount">
          <el-select
            v-model="formData.intakeAmount"
            placeholder="选择摄入量"
            style="width: 100%"
          >
            <el-option label="较少" value="较少" />
            <el-option label="正常" value="正常" />
            <el-option label="较多" value="较多" />
          </el-select>
        </el-form-item>
        <el-form-item label="特殊饮食" prop="specialDiet">
          <el-input
            v-model="formData.specialDiet"
            placeholder="请输入特殊饮食要求"
          />
        </el-form-item>
        <el-form-item label="营养信息" prop="nutritionInfo">
          <el-input
            v-model="formData.nutritionInfo"
            type="textarea"
            :rows="2"
            placeholder="请输入营养信息"
          />
        </el-form-item>
        <el-form-item label="反馈" prop="feedback">
          <el-input
            v-model="formData.feedback"
            type="textarea"
            :rows="2"
            placeholder="请输入长者反馈"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import {
  getCaregiverMealRecords,
  addMealRecord,
  updateMealRecord,
  deleteMealRecord,
  getEldersByCaregiver
} from '@/api/meal.js'
import dayjs from 'dayjs'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const submitting = ref(false)
const formRef = ref()
const elderList = ref([])

// 搜索参数
const searchParams = reactive({
  elderId: '',        // 长者ID（用于筛选）
  mealType: '',       // 餐饮类型（用于筛选）
  mealDate: ''        // 用餐日期（单个日期）
})

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref([])

// 表单数据 - 关键修复：初始化mealType默认值
const formData = reactive({
  mealId: null,
  elderId: '',
  mealType: '早餐',  // 初始化餐饮类型默认值为"早餐"
  mealTime: '',
  foodContent: '',
  intakeAmount: '正常',
  specialDiet: '',
  nutritionInfo: '',
  feedback: ''
})

// 表单验证规则
const formRules = {
  elderId: [{ required: true, message: '请选择长者', trigger: 'change' }],
  mealType: [{ required: true, message: '请选择餐饮类型', trigger: 'change' }],
  mealTime: [{ required: true, message: '请选择用餐时间', trigger: 'change' }],
  foodContent: [{ required: true, message: '请输入食物内容', trigger: 'blur' }],
  intakeAmount: [{ required: true, message: '请选择摄入量', trigger: 'change' }]
}

// 计算属性
const dialogTitle = computed(() => formData.mealId ? '编辑餐饮记录' : '新增餐饮记录')
const isEdit = computed(() => !!formData.mealId)

// 方法
const getMealTypeTag = (type) => {
  const tagMap = {
    '早餐': 'success',
    '午餐': 'warning',
    '晚餐': 'info',
    '加餐': 'primary'
  }
  return tagMap[type] || 'info'
}

const getIntakeTag = (amount) => {
  const tagMap = {
    '较少': 'warning',
    '正常': 'success',
    '较多': 'danger'
  }
  return tagMap[amount] || 'info'
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  // 如果是字符串格式的时间，直接返回
  if (typeof dateTime === 'string') {
    // 检查是否是有效的日期字符串
    if (!isNaN(Date.parse(dateTime))) {
      const date = new Date(dateTime)
      return `${date.getFullYear()}/${(date.getMonth() + 1).toString().padStart(2, '0')}/${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`
    }
    // 如果是已经格式化的字符串，直接返回
    return dateTime;
  }
  // 如果是日期对象，格式化为指定格式
  return `${dateTime.getFullYear()}/${(dateTime.getMonth() + 1).toString().padStart(2, '0')}/${dateTime.getDate().toString().padStart(2, '0')} ${dateTime.getHours().toString().padStart(2, '0')}:${dateTime.getMinutes().toString().padStart(2, '0')}:${dateTime.getSeconds().toString().padStart(2, '0')}`
}

// 加载数据
// 修改loadData方法中的参数处理
// 重新修改loadData方法中的参数处理
const loadData = async () => {
  loading.value = true;
  try {
    // 基础参数
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      caregiverId: await getCurrentCaregiverId()
    };

    // 仅在有值时添加筛选参数 - 关键修复
    if (searchParams.elderId) {
      params.elderId = Number(searchParams.elderId); // 转换为数字类型
    }
    if (searchParams.mealType) {
      params.mealType = searchParams.mealType;
    }
    if (searchParams.mealDate) {
      params.mealDate = dayjs(searchParams.mealDate).format('YYYY-MM-DD');
    }

    console.log('筛选参数:', params); // 打印参数用于调试

    const response = await getCaregiverMealRecords(params);
    console.log('接口返回数据:', response.data);

    // 处理返回数据
    tableData.value = response.data?.records || response.data || [];
    pagination.total = response.data?.total || tableData.value.length;
  } catch (error) {
    console.error('加载餐饮记录失败:', error);
    // 优化错误提示
    if (error.message.includes('For input string: ""')) {
      ElMessage.error('筛选失败：请选择有效的长者');
    } else {
      ElMessage.error('加载餐饮记录失败');
    }
  } finally {
    loading.value = false;
  }
};


// 加载护工负责的长者列表
// 加载护工负责的长者列表（修复版）
// 加载护工负责的长者列表（修复版）
const loadElderList = async () => {
  try {
    const caregiverId = await getCurrentCaregiverId();
    const res = await getEldersByCaregiver(caregiverId);

    // 关键修复：确保数据是数组
    const elderData = Array.isArray(res.data) ? res.data : (res.data?.records || []);

    elderList.value = elderData.map(item => ({
      elderId: item.elderId,
      name: item.name
    }));
  } catch (error) {
    console.error('加载老人列表失败', error);
    ElMessage.error('加载老人列表失败，请稍后重试');
  }
};

// 获取当前登录护工ID
const getCurrentCaregiverId = () => {
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
  return userInfo.caregiverId || ''
}

// 搜索处理
// 找到搜索处理方法并替换
// 修改搜索处理方法，增加显式刷新
// 调整搜索处理方法，移除强制清空
const handleSearch = () => {
  pagination.currentPage = 1;
  loadData(); // 直接加载，不强制清空现有数据
};

// 给下拉框增加显式的change事件处理（双重保障）
const handleElderChange = (value) => {
  searchParams.elderId = value;
  handleSearch();
};


// 分页处理
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

// 新增记录 - 关键修复：重置表单时设置默认值
const handleAdd = () => {
  Object.keys(formData).forEach(key => {
    if (key !== 'mealId') {
      formData[key] = ''
    }
  })
  formData.mealId = null
  formData.intakeAmount = '正常'
  formData.mealType = '早餐'  // 新增时设置默认餐饮类型
  dialogVisible.value = true
}

// 编辑记录
const handleEdit = (row) => {
  formData.mealId = row.mealId;
  formData.elderId = row.elderId;
  formData.mealType = row.mealType;  // 确保编辑时正确设置餐饮类型
  formData.mealTime = new Date(row.mealTime);
  formData.foodContent = row.foodContent;
  formData.intakeAmount = row.intakeAmount;
  formData.nutritionInfo = row.nutritionInfo;
  formData.specialDiet = row.specialDiet;
  formData.feedback = row.feedback;
  dialogVisible.value = true;
};

// 删除记录
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条餐饮记录吗？', '提示', {
      type: 'warning'
    })

    await deleteMealRecord(id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate();
    submitting.value = true;

    const payload = {
      ...formData,
      elderId: Number(formData.elderId),
      caregiverId: await getCurrentCaregiverId(),
    };

    // 处理时间字段
    if (payload.mealTime) {
      if (payload.mealTime instanceof Date) {
        // 如果是Date对象，转换为格式化字符串
        payload.mealTime = formatDateTime(payload.mealTime);
      } else if (typeof payload.mealTime === 'string') {
        // 如果已经是字符串，保持不变
        payload.mealTime = payload.mealTime;
      }
    }

    if (formData.mealId) {
      payload.id = formData.mealId;
      await updateMealRecord(payload);
    } else {
      delete payload.id;
      await addMealRecord(payload);
    }

    ElMessage.success('提交成功');
    dialogVisible.value = false;
    // 修改为强制刷新
    pagination.currentPage = 1;  // 回到第一页
    loadData();  // 重新加载数据
  } catch (error) {
    if (error.name !== 'Error') {
      console.error('表单验证失败:', error);
      return;
    }
    console.error('提交失败', error);
    ElMessage.error('提交失败：' + (error.response?.data?.message || '网络错误'));
  } finally {
    submitting.value = false;
  }
};

// 生命周期
onMounted(() => {
  loadElderList()
  loadData()
})
</script>


<style scoped>
.caregiver-meal-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  min-height: calc(100vh - 140px);
}

.header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e8e8e8;
}

.header h2 {
  margin: 0;
  color: #303133;
  font-size: 20px;
}

.header p {
  margin: 5px 0 0 0;
  color: #909399;
  font-size: 14px;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 6px;
}

.action-section {
  margin-bottom: 20px;
}

.table-section {
  margin-bottom: 20px;
}

.pagination-section {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table .cell) {
  word-break: break-word;
}
</style>
